package 
{
	import flash.display.Sprite;
	import flash.desktop.NativeApplication;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import com.quetwo.Arduino.ArduinoConnector;
	import com.quetwo.Arduino.ArduinoConnectorEvent;
	
	
	/**
	 * @author yaempechenki@gmail.com
	 */
	public class Main extends Sprite 
	{
		public var arduino:ArduinoConnector;
		private const PORT_SPEED:int = 9600;
		private var PING_UIDS:String = "5929406";
		private var _trayIconHelper:TrayIconHelper = null;
		private var _view:View = null;
		private var _previousPingEvent:String = "";
		private var _pingHelper:PingHelper = null;
		public function Main():void 
		{
			initApp();
		}
		
		private function initApp():void
		{
			_view = new View();
			_view.addEventListener(AppEvent.APP_CLOSE, exitApplication);
			_view.addEventListener(AppEvent.APP_TO_TRAY, goToTray);
			_view.addEventListener(AppEvent.APP_COMMAND_ON, sendCommandToRs232);
			_view.addEventListener(AppEvent.APP_COMMAND_OFF, sendCommandToRs232);
			_view.addEventListener(AppEvent.APP_PORT_SELECT, setPort);
			addChild(_view);
			
			_trayIconHelper = new TrayIconHelper(stage);
			_trayIconHelper.addEventListener(AppEvent.APP_CLOSE, exitApplication);
			
			
			
			arduino = new ArduinoConnector();
			var ports:Array = [];
			ports = arduino.getComPorts();
			ports.unshift("Select port..");
			_view.showPorts(ports);
		}
		
		private function connect():void {
			arduino.connect(_view.port, PORT_SPEED);
			
			_pingHelper = new PingHelper(PING_UIDS);
			_pingHelper.addEventListener(AppEvent.APP_COMMAND_OFF, pingHandler);
			_pingHelper.addEventListener(AppEvent.APP_COMMAND_ON, pingHandler);
			
			stage.addEventListener(MouseEvent.MOUSE_DOWN, drugnme);
		}
		
		private function pingHandler(event:Event):void {
			if (_previousPingEvent != event.type) {
				_previousPingEvent  = event.type;
				_view.connectionState = (event.type == AppEvent.APP_COMMAND_ON);
				sendCommandToRs232(event);
			}
		}
		private function sendCommandToRs232(event:Event):void {
			trace("send command   " + event.type);
			if(!arduino.portOpen) return;
			if (event.type == AppEvent.APP_COMMAND_ON) {
				arduino.writeString("a");
			}
			
			if (event.type == AppEvent.APP_COMMAND_OFF) {
				arduino.writeString("b");
			}
		}
		
		private function setPort(event:Event):void {
			connect();
		}
		
		private function goToTray(event:Event):void {
			_trayIconHelper.showTray();
		}
		
		private function exitApplication(event:Event):void {
			arduino.dispose();
			_trayIconHelper.fromTray();
			NativeApplication.nativeApplication.exit();
		}
		
		private function drugnme(event:MouseEvent):void{
			stage.nativeWindow.startMove()
		}
		
		
	}
	
}